﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Net.Http.Json;
using System.Xml.Linq;

namespace Jsonp.Server.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class JsonpController : ControllerBase
    {
        [HttpGet("{action}")]
        public IActionResult GetDataByJavaScript()
        {
            string jsonpData = GetJsonpData(
                Request.Query["jsoncallback"],
                JsonConvert.SerializeObject(new { success = true, message = "hello jsonp!!" })
                );
            return Content(jsonpData);
        }

        private string GetJsonpData(string callbackName, string json)
        {
            string data = $"{callbackName}({json})";
            return data;
        }

        [HttpGet("{action}")]
        public async Task GetData()
        {

            string callbackName = Request.Query["callback"];

            string jsonCntent = JsonConvert.SerializeObject(new { success = true, message = "hello jsonp!!" });

            string callFunc = callbackName + $"({jsonCntent})";

            await Response.WriteAsync(callFunc);
        }
    }
}
